package sf.database.jdbc.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Date;

/**
 * java.util.Date<---->long 转换
 */
public class DateLongType implements TypeHandler<Date> {
    public Date get(ResultSet rs, String colName) throws SQLException {
        long re = rs.getLong(colName);
        return rs.wasNull() ? null : new Date(re);
    }

    public Date get(ResultSet rs, int index) throws SQLException {
        long re = rs.getLong(index);
        return rs.wasNull() ? null : new Date(re);
    }

    public Date get(CallableStatement rs, int index) throws SQLException {
        long re = rs.getLong(index);
        return rs.wasNull() ? null : new Date(re);
    }

    @Override
    public Date get(CallableStatement cs, String parameterName) throws SQLException {
        long re = cs.getLong(parameterName);
        return cs.wasNull() ? null : new Date(re);
    }

    @Override
    public void update(ResultSet rs, String columnLabel, Object value) throws SQLException {
        rs.updateLong(columnLabel, changeLongType(value));
    }

    @Override
    public void update(ResultSet rs, int columnIndex, Object value) throws SQLException {
        rs.updateLong(columnIndex, changeLongType(value));
    }

    public Object set(PreparedStatement stat, Object value, int index) throws SQLException {
        if (null == value) {
            stat.setNull(index, getSqlType());
        } else {
            stat.setLong(index, changeLongType(value));
        }
        return null;
    }

    @Override
    public Object set(CallableStatement cs, Object value, String parameterName) throws SQLException {
        if (null == value) {
            cs.setNull(parameterName, getSqlType());
        } else {
            cs.setLong(parameterName, changeLongType(value));
        }
        return null;
    }

    @Override
    public int getSqlType() {
        return Types.BIGINT;
    }

    @Override
    public Class<Date> getDefaultJavaType() {
        return Date.class;
    }

    protected static long changeLongType(Object value) {
        if (Long.class.isAssignableFrom(value.getClass())) {
            return (long) value;
        } else if (Date.class.isAssignableFrom(value.getClass())) {
            return ((Date) value).getTime();
        }
        return 0L;
    }
}
